package com.etrans.baf.analyse.task.track.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.etrans.baf.analyse.task.track.domain.Vehicle;
import com.etrans.baf.analyse.util.BaseService;
import com.etrans.baf.analyse.util.Constants;
import com.etrans.baf.analyse.util.DateUtils;
import com.etrans.baf.analyse.util.SpringWebContextUtil;
import com.etrans.baf.analyse.util.Sysconfig;
import com.etrans.baf.analyse.util.XmlReader;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MapReduceCommand;
import com.mongodb.MapReduceOutput;

@Service
public class TouristVehicleOutService extends BaseService {

	static final Logger logger = LoggerFactory.getLogger(TouristVehicleOutService.class);

	@Autowired
	private MongoTemplate egovMongoTemplate;// 引入配置的mongod模版
	
	public MongoTemplate getEgovMongoTemplate() {
		return egovMongoTemplate;
	}
	public TouristVehicleOutService() {
		super.masterAliases = "com.etrans.baf.analyse.task.track.persistence.trackMapper";
 	}
	
	/**
	 * 旅游车出贵阳
	 */
	public void touristVehicleOut(String analyse_date) throws Exception {
		// 先删除后新增
		Date analyseDate = DateUtils.parse(analyse_date, Constants.DATE_YYYY_MM_DD);
		String dirUrl = System.getProperty("analyse") + Sysconfig.getPropValueByCode("track");
		String table_date = DateUtils.format(analyseDate, Constants.DATE_YYMMDD);
		List<Vehicle> list = getTouristVehicle();
		HashMap<Integer,Vehicle> vMap = new HashMap<Integer,Vehicle>();
		for (Vehicle v : list) {
			vMap.put(v.getId(), v);
		}
		mapreduceTouristVehicleOut(dirUrl, analyseDate, table_date,vMap);
	}

	/*
	 * 旅游车
	 */
	@SuppressWarnings("unchecked")
	private List<Vehicle> getTouristVehicle(){
		return (List<Vehicle>) this.select("getTouristVehicle", null);
	}
	
	private void mapreduceTouristVehicleOut(String dirUrl, Date analyseDate, String table_date,HashMap<Integer,Vehicle> vMap) {
		long st = System.nanoTime() ;
		Map<String, String> map = XmlReader.readXmlToMapReduce(dirUrl + "tourist_vehicle_out_guiyang.xml");
		if (map != null && map.size() > 0) {
			DBObject sort = new BasicDBObject();
			sort.put("_id", 1);
			DBCollection db = egovMongoTemplate.getDb().getCollection("gps_info_" + table_date);
			MapReduceCommand cmd = new MapReduceCommand(db, map.get("map"), map.get("reduce"),
					"tourist_vehicle_out_guiyang_" + System.currentTimeMillis(), MapReduceCommand.OutputType.REPLACE,null);
			cmd.setFinalize(map.get("finalize"));
			cmd.setSort(sort);
			MapReduceOutput out = db.mapReduce(cmd);
			DBCollection resultColl = out.getOutputCollection();
			String o_name = resultColl.getName();
			DBCursor cursor = resultColl.find();
			List<DBObject> list = new ArrayList<DBObject>();
			Map<String,DBObject> dataMap = new HashMap<>() ;
			if (cursor != null) {
				while(cursor.hasNext()) {
					try {
						DBObject dbObject = cursor.next() ;
						DBObject obj = (DBObject) dbObject.get("value") ;
						DBObject _id = (DBObject) dbObject.get("_id") ;
						String vehicleNo = (String) _id.get("vehicle_no") ;
						Integer vehicleColor = (int)_id.get("vehicle_color") ;
						Integer vehicleId = (int)_id.get("vehicle_id") ;
						Object coordinatesObj = obj.get("coordinates") ;
						if(vMap.get(vehicleId) != null) {
							if(coordinatesObj.getClass().equals(BasicDBList.class)) {
								BasicDBList coordinatesList = (BasicDBList) obj.get("coordinates") ;
								BasicDBList insideList = (BasicDBList) obj.get("inside") ;
								BasicDBList gpsList = (BasicDBList)obj.get("gps_time") ;
								boolean b = false ;
								for(int k = 0 ;k < insideList.size() ; k++) {
									if((Double)insideList.get(k) - 1 == 0) {
										b = true ;
									}
									if(b) {
										if((k+1) < insideList.size() && (Double)insideList.get(k+1) - 0 == 0){
											 DBObject dbobj = new BasicDBObject() ;
											 String id = table_date+":"+vehicleNo+":"+vehicleColor ;
											 dbobj.put("_id", id) ;
											 dbobj.put("vehicle_no", vehicleNo) ;
											 dbobj.put("vehicle_color", vehicleColor) ;
											 dbobj.put("analyse_date", analyseDate) ;
											 dbobj.put("gps_time", (Date)gpsList.get(k+1)) ;
											 dbobj.put("coordinates", coordinatesList.get(k+1)) ;
											 dataMap.put(id, dbobj) ;
											 b = false ;
										 }
									}
								}
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			for(String str : dataMap.keySet()) {
				list.add(dataMap.get(str)) ;
			}
			if (list.size() > 0) {
				Query rquery = Query.query(Criteria.where("analyse_date").is(analyseDate));
	        	int count = egovMongoTemplate.remove(rquery, "tourist_vehicle_out_guiyang").getN();
	        	if(count>0){
	        		logger.info("删除已经分析过的旅游车出贵阳数据"+count+"条");
	        	}
				egovMongoTemplate.insert(list, "tourist_vehicle_out_guiyang");
				logger.info("入库" + list.size() + "到tourist_vehicle_out_guiyang中");
			}
			egovMongoTemplate.dropCollection(o_name);// 用完后删除
		}
		logger.info("用时："+(System.nanoTime() - st)/1000000000+"秒");
	}

	protected SqlSessionTemplate getMasterSessionTemplate() {
		return (SqlSessionTemplate) SpringWebContextUtil.getApplicationContext().getBean("dataSourceMasterSession");
	}

}
